/**
 * 生成 Mock 数据脚本
 * 生成 500 条员工和对应的班次数据
 */

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 姓氏和名字池
const surnames = [
  '张',
  '李',
  '王',
  '刘',
  '陈',
  '杨',
  '赵',
  '黄',
  '周',
  '吴',
  '徐',
  '孙',
  '胡',
  '朱',
  '高',
  '林',
  '何',
  '郭',
  '马',
  '罗',
]
const names = [
  '伟',
  '芳',
  '娜',
  '秀英',
  '敏',
  '静',
  '丽',
  '强',
  '磊',
  '军',
  '洋',
  '勇',
  '艳',
  '杰',
  '涛',
  '明',
  '超',
  '秀兰',
  '霞',
  '平',
]
// 部门配置（类似甘特图的床型分类）
const departments = [
  { name: '技术部', color: '#E3F2FD' },
  { name: '产品部', color: '#F3E5F5' },
  { name: '运营部', color: '#E8F5E9' },
  { name: '市场部', color: '#FFF3E0' },
  { name: '人事部', color: '#FCE4EC' },
  { name: '财务部', color: '#E0F2F1' },
]

const positions = [
  '前台',
  '服务员',
  '厨师',
  '清洁工',
  '经理',
  '保安',
  '收银员',
  '主管',
  '助理',
  '学徒',
  '领班',
  '技师',
  '顾问',
  '专员',
  '总监',
]

// 生成随机姓名
function generateName() {
  const surname = surnames[Math.floor(Math.random() * surnames.length)]
  const name = names[Math.floor(Math.random() * names.length)]
  return surname + name
}

// 生成随机职位
function generatePosition() {
  return positions[Math.floor(Math.random() * positions.length)]
}

// 格式化日期为 YYYY-MM-DD
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生成员工数据（按部门分组，类似甘特图床型分组）
function generateEmployees(count) {
  const employees = []
  const employeesPerDept = Math.ceil(count / departments.length)

  let id = 1
  for (const dept of departments) {
    // 为每个部门生成员工
    const deptCount = Math.min(employeesPerDept, count - employees.length)
    for (let i = 0; i < deptCount; i++) {
      employees.push({
        id: id++,
        name: generateName(),
        department: dept.name, // 部门名称
        departmentColor: dept.color, // 部门颜色
        position: generatePosition(),
        phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
        email: `employee${id - 1}@company.com`,
        status: 'active',
        hireDate: formatDate(
          new Date(2020 + Math.floor(Math.random() * 5), Math.floor(Math.random() * 12), 1)
        ),
      })
    }
  }
  return employees
}

// 将时间字符串转换为小时数（例如 "08:00" -> 8）
function timeToHours(timeStr) {
  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours + minutes / 60
}

// 生成班次数据
// 规则：
// 1. 所有31天都有排班（每个员工随机60-70%的天数有班）
// 2. 每个班次最长8小时
// 3. 两次班次之间至少休息16小时
function generateShifts(employees, daysCount = 31) {
  const shifts = []
  let shiftId = 1

  const today = new Date()
  today.setHours(0, 0, 0, 0) // 重置到当天0点

  // 预定义的班次时间（都是8小时）- 均衡分配早中晚班
  const shiftTemplates = [
    // 早班 (6个)
    { type: 'morning', startTime: '06:00', endTime: '14:00', name: '早班' },
    { type: 'morning', startTime: '07:00', endTime: '15:00', name: '早班' },
    { type: 'morning', startTime: '08:00', endTime: '16:00', name: '早班' },
    { type: 'morning', startTime: '09:00', endTime: '17:00', name: '早班' },
    { type: 'morning', startTime: '10:00', endTime: '18:00', name: '早班' },
    { type: 'morning', startTime: '11:00', endTime: '19:00', name: '早班' },
    // 中班 (6个)
    { type: 'afternoon', startTime: '12:00', endTime: '20:00', name: '中班' },
    { type: 'afternoon', startTime: '13:00', endTime: '21:00', name: '中班' },
    { type: 'afternoon', startTime: '14:00', endTime: '22:00', name: '中班' },
    { type: 'afternoon', startTime: '15:00', endTime: '23:00', name: '中班' },
    { type: 'afternoon', startTime: '16:00', endTime: '24:00', name: '中班' },
    { type: 'afternoon', startTime: '17:00', endTime: '01:00', name: '中班' },
    // 夜班 (4个)
    { type: 'night', startTime: '20:00', endTime: '04:00', name: '夜班' },
    { type: 'night', startTime: '22:00', endTime: '06:00', name: '夜班' },
    { type: 'night', startTime: '00:00', endTime: '08:00', name: '夜班' },
    { type: 'night', startTime: '02:00', endTime: '10:00', name: '夜班' },
  ]

  // 三班倒模式：早班 -> 中班 -> 夜班
  const shiftCycle = ['morning', 'afternoon', 'night']

  employees.forEach(employee => {
    let cycleIndex = Math.floor(Math.random() * 3) // 随机起始班次
    let consecutiveDays = 0 // 连续工作天数

    for (let day = 0; day < daysCount; day++) {
      const currentDate = new Date(today)
      currentDate.setDate(today.getDate() + day)

      // 工作2-3天后休息1天
      if (consecutiveDays >= 2 && Math.random() < 0.4) {
        consecutiveDays = 0
        continue // 休息日
      }

      // 获取当前应该上的班次类型
      const currentShiftType = shiftCycle[cycleIndex]

      // 从对应类型的班次中随机选择
      const availableShifts = shiftTemplates.filter(t => t.type === currentShiftType)
      const selectedTemplate = availableShifts[Math.floor(Math.random() * availableShifts.length)]

      shifts.push({
        id: shiftId++,
        employeeId: employee.id,
        employeeName: employee.name,
        date: formatDate(currentDate),
        type: selectedTemplate.type,
        startTime: selectedTemplate.startTime,
        endTime: selectedTemplate.endTime,
        status: 'confirmed',
        note: Math.random() > 0.9 ? '正常排班' : '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      })

      consecutiveDays++
      // 切换到下一个班次类型
      cycleIndex = (cycleIndex + 1) % 3
    }
  })

  return shifts
}

// 生成数据
console.log('🔄 生成 Mock 数据中...')

const employees = generateEmployees(80) // 生成80个员工
const shifts = generateShifts(employees, 31) // 31天：今天 + 未来30天

const mockData = {
  employees,
  shifts,
}

// 写入文件
const outputPath = path.join(__dirname, '../public/db.json')
fs.writeFileSync(outputPath, JSON.stringify(mockData, null, 2), 'utf-8')

console.log('✅ Mock 数据生成成功！')
console.log(`📊 员工数量: ${employees.length}`)
console.log(`📅 班次数量: ${shifts.length}`)
console.log(`📁 文件路径: ${outputPath}`)
